/**
 * 常用公共的方法
 * @author yangxiao
 * @module app/game/common-function
 */

import * as ws from 'ws';
import * as serverConfig from '../../lib/config/config'
import * as sws from '../../lib/net/server-websocket';
import * as wsEvent from '../../lib/net/event-websocket';
import * as protobuf from '../../lib/protobuf/protobuf-msg';
import * as msgSend from '../../util/get-send-function';
import * as log from '../../lib/log/log'
import * as moduleRegister from './module-register';



/**
 * 发送到主服务器
 * @param {protoBufMsg.msg_base_s2s} msg_base_s2s
 */
export function sendMasterServer(msg_base_s2s:protoBufMsg.msg_base_s2s){

    let clients = _gameServer.getClients();
    let len = clients.length;
    clients.forEach((values,index,array)=>{
        if(values.upgradeReq.headers.serverid==msg_base_s2s.serverID){
            msgSend.send(msg_base_s2s,values,__filename);
        }
    });
}


export let _gameServer:sws.ServerWebSocket;


export function register(){

    let config = serverConfig.getServerConfig();
    let len = config.ServerGameList.length;
    for(let i=0;i<len;++i){
        if(config.ServerGameList[i].id==serverConfig.serverID){
     
            if(_gameServer==null){
                _gameServer = new sws.ServerWebSocket();
                _gameServer.createServer(config.ServerGameList[i].port);
                _gameServer.on(wsEvent.Event.clientMessage,_gameMessage);
            }
            return;
        }
    }
}

export function _gameMessage(message:any,client:ws){ 
 
    try{
        let classList = protobuf.getMsgProto();
        let msg_base_s2s = classList.msg_base_s2s.decode(message);
        msg_base_s2s.serverID =  client.upgradeReq.headers.serverid;
        moduleRegister.excModuleMain(msg_base_s2s.msg_code,msg_base_s2s.serverID,msg_base_s2s);
    }catch(e){
        client.close(1000,"error message Illegal format");
        return;
    }
}